﻿using Kingdee.BOS.Collections.Generic;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.List.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.NotePrint;
using Kingdee.BOS.JSON;
using Kingdee.BOS.KDThread;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.ServiceHelper.Report;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace LianKe.ListPlugIn
{
    [Description("引出文件插件"), HotUpdate]

    public class BackgroundPrintTaskListPlugIn : AbstractListPlugIn
    {
        //public override void PrepareFilterParameter(FilterArgs e)
        //{
        //    ((AbstractListPlugIn)this).PrepareFilterParameter(e);
        //    e.AppendQueryFilter("FCreatorId=" + ((AbstractDynamicFormPlugIn)this).Context.UserId);
        //    e.SortString = "FCreateDate";
        //}
        public override void PrepareFilterParameter(FilterArgs e)
        {
            base.PrepareFilterParameter(e);
            e.AppendQueryFilter("FCreatorId=" + ((AbstractDynamicFormPlugIn)this).Context.UserId);
            e.SortString = "FCreateDate";
        }
        public override void ListRowDoubleClick(ListRowDoubleClickArgs e)
        {
            e.Cancel = true;
            base.ListRowDoubleClick(e);
        }
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            switch (e.BarItemKey.ToUpperInvariant())
            {
                case "TBADD":
                    AddTask();
                    break;
                case "TBPRINT":
                    Print();
                    break;
                case "TBPRINTPREVIEW":
                    Print(preview: true);
                    break;
                case "TBEXPORT":
                    Export();
                    break;
                case "TBDEL":
                    Del(e);
                    break;
                case "TBQUIT":
                    ((AbstractDynamicFormPlugIn)this).View.Close();
                    break;
            }
        }

        private void Del(BarItemClickEventArgs e)
        {
            e.Cancel = true;
            if (((Collection<ListSelectedRow>)(object)((AbstractListPlugIn)this).ListView.SelectedRowsInfo).Count <= 0)
            {
                ((AbstractDynamicFormPlugIn)this).View.ShowWarnningMessage(ResManager.LoadKDString("没有选择任何数据，请先选择数据！", "002012030003253", (SubSystemType)2, new object[0]), "", (MessageBoxOptions)0, (Action<MessageBoxResult>)null, (MessageBoxType)1);
                return;
            }
            string text = ResManager.LoadKDString("请确认是否删除选定的记录？", "002014030027828", (SubSystemType)2, new object[0]);
            ((AbstractDynamicFormPlugIn)this).View.ShowMessage(text, (MessageBoxOptions)4, (Action<MessageBoxResult>)delegate (MessageBoxResult result)
            {
                //IL_0000: Unknown result type (might be due to invalid IL or missing references)
                //IL_0002: Invalid comparison between Unknown and I4
                if ((int)result == 6)
                {
                    ((AbstractDynamicFormPlugIn)this).View.InvokeFormOperation("Delete");
                }
            }, "", (MessageBoxType)0);
        }

        private void Export()
        {
            if (((Collection<ListSelectedRow>)(object)((AbstractListPlugIn)this).ListView.SelectedRowsInfo).Count <= 0)
            {
                ((AbstractDynamicFormPlugIn)this).View.ShowWarnningMessage(ResManager.LoadKDString("没有选择任何数据，请先选择数据！", "002012030003253", (SubSystemType)2, new object[0]), "", (MessageBoxOptions)0, (Action<MessageBoxResult>)null, (MessageBoxType)1);
                return;
            }
            List<int> list = new List<int>();
            List<string> list2 = new List<string>();
            foreach (ListSelectedRow item in (Collection<ListSelectedRow>)(object)((AbstractListPlugIn)this).ListView.SelectedRowsInfo)
            {
                if (item.DataRow["FActionTypeId"] != null && (Convert.ToInt32(item.DataRow["FActionTypeId"]) == 5 || Convert.ToInt32(item.DataRow["FActionTypeId"]) == 10) && item.DataRow["FStatus"] != null && Convert.ToInt32(item.DataRow["FStatus"]) == 2)
                {
                    list2.Add(item.PrimaryKeyValue);
                }
                else
                {
                    list.Add(item.RowKey);
                }
            }
            if (list2.Count <= 0)
            {
                ((AbstractDynamicFormPlugIn)this).View.ShowWarnningMessage(ResManager.LoadKDString("当前选择的数据中不包含有效数据，请勾选任务类型为引出，任务状态为已处理的数据！", "002014000004494", (SubSystemType)2, new object[0]), "", (MessageBoxOptions)0, (Action<MessageBoxResult>)null, (MessageBoxType)1);
                return;
            }
            string[] ids = list2.ToArray();
            if (list.Count > 0)
            {
                string text = string.Format(ResManager.LoadKDString("数据行[{0}]无法引出，请确认是否继续引出？", "002014000004490", (SubSystemType)2, new object[0]), string.Join(",", list));
                ((AbstractDynamicFormPlugIn)this).View.ShowMessage(text, (MessageBoxOptions)4, (Action<MessageBoxResult>)delegate (MessageBoxResult result)
                {
                    //IL_0000: Unknown result type (might be due to invalid IL or missing references)
                    //IL_0002: Invalid comparison between Unknown and I4
                    if ((int)result == 6)
                    {
                        DoExportAsync(ids);
                    }
                }, "", (MessageBoxType)0);
            }
            else
            {
                DoExportAsync(ids);
            }
        }

        private void DoExportAsync(string[] ids)
        {
            ViewUtils.ShowProcessForm(((AbstractDynamicFormPlugIn)this).View, (Action<FormResult>)delegate
            {
            }, true, ResManager.LoadKDString("引出中..", "002014030036064", (SubSystemType)2, new object[0]));
            MainWorker.QuequeTask(((AbstractDynamicFormPlugIn)this).View.Context, (Action)delegate
            {
                try
                {
                    DoExport(ids);
                }
                finally
                {
                    ((AbstractDynamicFormPlugIn)this).View.Session["ProcessRateValue"] = 100;
                    ((AbstractDynamicFormPlugIn)this).View.SendDynamicFormAction(((AbstractDynamicFormPlugIn)this).View);
                }
            }, (Action<AsynResult>)delegate
            {
            });
        }

        private void DoExport(string[] ids)
        {
            DynamicObjectCollection printTaskList = BackgroundPrintServiceHelper.GetPrintTaskList(((AbstractDynamicFormPlugIn)this).Context, ids);
            foreach (DynamicObject item in (Collection<DynamicObject>)(object)printTaskList)
            {
                string text = item["FID"].ToString();
                DynamicObjectCollection printDataList = BackgroundPrintServiceHelper.GetPrintDataList(((AbstractDynamicFormPlugIn)this).Context, text, true);
                if (ListUtils.IsEmpty<DynamicObject>((IEnumerable<DynamicObject>)printDataList))
                {
                    ((AbstractDynamicFormPlugIn)this).View.ShowMessage(ResManager.LoadKDString("无数据可引出！", "002014000006879", (SubSystemType)2, new object[0]), (MessageBoxType)0);
                    break;
                }
                PrintExportInfo val = KDObjectConverter.DeserializeObject<PrintExportInfo>(item["FPrintParamter"].ToString());
                List<string> list = new List<string>();
                for (int i = 0; i < ((Collection<DynamicObject>)(object)printDataList).Count; i++)
                {
                    DynamicObject val2 = ((Collection<DynamicObject>)(object)printDataList)[i];
                    GetExportFileName(val, item["FTaskNAME"].ToString(), out var filePath, out var fileUrl, i);
                    byte[] bytes = Convert.FromBase64String(val2["FPRINTDATA"].ToString());
                    try
                    {
                        File.WriteAllBytes(filePath, bytes);
                        if (((KeyedCollectionBase<string, DynamicProperty>)(object)item.DynamicObjectType.Properties).ContainsKey("FACTIONTYPEID") && ObjectUtils.Object2Int(item["FACTIONTYPEID"], 0) == 5)
                        {
                            UpdateNotePrintExportTimes(val);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        ((AbstractDynamicFormPlugIn)this).View.ShowErrMessage(string.Format(ResManager.LoadKDString("IIS进程没有足够的权限来写入文件{0}，请联系服务器管理员对文件夹{1}给用户EveryOne赋予足够的操作权限", "002014000004491", (SubSystemType)2, new object[0]), filePath, PathUtils.GetPhysicalPath(KeyConst.TEMPFILEPATH)), "", (MessageBoxType)0);
                    }
                    catch (Exception ex2)
                    {
                        ((AbstractDynamicFormPlugIn)this).View.ShowErrMessage(ResManager.LoadKDString("文件写入失败:", "002014000004492", (SubSystemType)2, new object[0]) + ex2.Message, "", (MessageBoxType)0);
                    }
                    list.Add(fileUrl);
                }
                if (list.Count > 0)
                {
                    if (list.Count == 1)
                    {
                        DownLoadFile(list[0], item["FTaskNAME"].ToString());
                    }
                    else
                    {
                        DownLoadFiles(list);
                    }
                }
            }
        }

        private void DownLoadFiles(List<string> urls)
        {
            DynamicFormShowParameter val = new DynamicFormShowParameter();
            val.FormId = "BOS_FileDownLoad";
            val.OpenStyle.ShowType = (ShowType)6;
            val.CustomParams.Add("IsExportData", "true");
            val.CustomComplexParams.Add("urls", urls);
            ((AbstractDynamicFormPlugIn)this).View.ShowForm(val);
        }

        private void DownLoadFile(string url, string linkText)
        {
            DynamicFormShowParameter val = new DynamicFormShowParameter();
            val.FormId = "BOS_FileDownLoad";
            val.OpenStyle.ShowType = (ShowType)6;
            val.CustomParams.Add("IsExportData", "true");
            val.CustomParams.Add("url", url);
            val.CustomParams.Add("linktext", linkText);
            ((AbstractDynamicFormPlugIn)this).View.ShowForm(val);
        }

        private void UpdateNotePrintExportTimes(PrintExportInfo pExInfo)
        {
            if (pExInfo != null && !ListUtils.IsEmpty<string>((IEnumerable<string>)pExInfo.BillIds) && !StringUtils.IsEmpty(pExInfo.FormId))
            {
                FormMetadata cachedFormMetaData = FormMetaDataCache.GetCachedFormMetaData(((AbstractDynamicFormPlugIn)this).View.Context, pExInfo.FormId);
                if ((cachedFormMetaData != null && cachedFormMetaData.BusinessInfo != null && ((AbstractElement)cachedFormMetaData.BusinessInfo.GetForm()).ElementType == 400) || ((AbstractElement)cachedFormMetaData.BusinessInfo.GetForm()).ElementType == 100)
                {
                    PrintServiceHelper.UpdatePrintExportTimes(((AbstractDynamicFormPlugIn)this).View.Context, cachedFormMetaData.BusinessInfo, pExInfo.BillIds);
                }
            }
        }

        private void GetExportFileName(PrintExportInfo pe, string taskName, out string filePath, out string fileUrl, int partIndex = 0)
        {
            string text = taskName + "_" + DateTime.Now.ToString("yyyyMMddHHmmssff");
            if (partIndex > 0)
            {
                text = text + "_part" + partIndex;
            }
            text = (((int)pe.FileType == 0) ? (text + ".xlsx") : (((int)pe.FileType != 2) ? (text + ".xls") : (text + ".pdf")));
            text = PathUtils.GetValidFileName(text);
            fileUrl = PathUtils.GetServerPath(KeyConst.TEMPFILEPATH, PathUtils.UrlEncode(text));
            filePath = PathUtils.GetPhysicalPath(KeyConst.TEMPFILEPATH, text);
        }

        private void Print(bool preview = false)
        {
            if (((Collection<ListSelectedRow>)(object)((AbstractListPlugIn)this).ListView.SelectedRowsInfo).Count <= 0)
            {
                ((AbstractDynamicFormPlugIn)this).View.ShowWarnningMessage(ResManager.LoadKDString("没有选择任何数据，请先选择数据！", "002012030003253", (SubSystemType)2, new object[0]), "", (MessageBoxOptions)0, (Action<MessageBoxResult>)null, (MessageBoxType)1);
                return;
            }
            List<int> list = new List<int>();
            List<string> list2 = new List<string>();
            foreach (ListSelectedRow item in (Collection<ListSelectedRow>)(object)((AbstractListPlugIn)this).ListView.SelectedRowsInfo)
            {
                if (item.DataRow["FActionTypeId"] != null && Convert.ToInt32(item.DataRow["FActionTypeId"]) == 0 && item.DataRow["FStatus"] != null && Convert.ToInt32(item.DataRow["FStatus"]) == 2)
                {
                    list2.Add(item.PrimaryKeyValue);
                }
                else
                {
                    list.Add(item.RowKey);
                }
            }
            if (list2.Count <= 0)
            {
                ((AbstractDynamicFormPlugIn)this).View.ShowWarnningMessage(ResManager.LoadKDString("当前选择的数据中不包含有效数据，请勾选任务类型为打印，任务状态为已处理的数据！", "002014000004493", (SubSystemType)2, new object[0]), "", (MessageBoxOptions)0, (Action<MessageBoxResult>)null, (MessageBoxType)1);
                return;
            }
            string[] ids = list2.ToArray();
            if (list.Count > 0)
            {
                string text = string.Format(ResManager.LoadKDString("数据行[{0}]无法打印，请确认是否继续打印？", "002014000004411", (SubSystemType)2, new object[0]), string.Join(",", list));
                ((AbstractDynamicFormPlugIn)this).View.ShowMessage(text, (MessageBoxOptions)4, (Action<MessageBoxResult>)delegate (MessageBoxResult result)
                {
                    //IL_0000: Unknown result type (might be due to invalid IL or missing references)
                    //IL_0002: Invalid comparison between Unknown and I4
                    if ((int)result == 6)
                    {
                        DoPrintAsync(ids, preview);
                    }
                }, "", (MessageBoxType)0);
            }
            else
            {
                DoPrintAsync(ids, preview);
            }
        }

        private void DoPrintAsync(string[] ids, bool preview = false, string printBarName = null)
        {
            ViewUtils.ShowProcessForm(((AbstractDynamicFormPlugIn)this).View, (Action<FormResult>)delegate
            {
            }, true, ResManager.LoadKDString("打印中..", "002014030036063", (SubSystemType)2, new object[0]));
            MainWorker.QuequeTask(((AbstractDynamicFormPlugIn)this).View.Context, (Action)delegate
            {
                try
                {
                    DoPrint(ids, preview, printBarName);
                }
                finally
                {
                    ((AbstractDynamicFormPlugIn)this).View.Session["ProcessRateValue"] = 100;
                    ((AbstractDynamicFormPlugIn)this).View.SendDynamicFormAction(((AbstractDynamicFormPlugIn)this).View);
                }
            }, (Action<AsynResult>)delegate
            {
            });
        }

        private void DoPrint(string[] ids, bool preview = false, string printBarName = null)
        {
            DynamicObjectCollection printTaskList = BackgroundPrintServiceHelper.GetPrintTaskList(((AbstractDynamicFormPlugIn)this).Context, ids);
            foreach (DynamicObject item in (Collection<DynamicObject>)(object)printTaskList)
            {
                string text = item["FID"].ToString();
                DynamicObjectCollection printDataList = BackgroundPrintServiceHelper.GetPrintDataList(((AbstractDynamicFormPlugIn)this).Context, text, false);
                if (ListUtils.IsEmpty<DynamicObject>((IEnumerable<DynamicObject>)printDataList))
                {
                    ((AbstractDynamicFormPlugIn)this).View.ShowMessage(ResManager.LoadKDString("无数据可打印！", "002014000004413", (SubSystemType)2, new object[0]), (MessageBoxType)0);
                    break;
                }
                IDynamicFormView value = BackgroundPrintServiceHelper.CreateView(((AbstractDynamicFormPlugIn)this).View.Context, item, false);
                ((AbstractDynamicFormPlugIn)this).View.Session["View_" + text] = value;
                string text2 = "print";
                bool flag = Convert.ToInt32(item["FOperationTypeId"]) == 5;
                if (!preview)
                {
                    if (flag)
                    {
                        text2 = "PrintMerge";
                    }
                }
                else
                {
                    text2 = (flag ? "PrintMergePreview" : "preview");
                }
                foreach (DynamicObject item2 in (Collection<DynamicObject>)(object)printDataList)
                {
                    string text3 = item2["FENTRYID"].ToString();
                    string text4 = (string.IsNullOrWhiteSpace(item2["FPRINTERNAME"].ToString()) ? string.Empty : item2["FPRINTERNAME"].ToString());
                    JSONObject val = new JSONObject();
                    val.Put("pageID", (object)((AbstractDynamicFormPlugIn)this).View.PageId);
                    val.Put("printJobId", (object)text3);
                    val.Put("action", (object)text2);
                    val.Put("dataMethod", (object)"GetBackgroundReport");
                    string text5;
                    if (preview)
                    {
                        text5 = "printPreview";
                        val.Put("printBarName", (object)printBarName);
                    }
                    else
                    {
                        text5 = "print";
                    }
                    val.Put("printerAddress", (object)text4);
                    List<PrintJob> printJob = KDObjectConverter.DeserializeObject<List<PrintJob>>(item["fprintparamter"].ToString());
                    NotePrintParameterBase val2 = new NotePrintParameterBase(text3, ((AbstractDynamicFormPlugIn)this).View);
                    val2.PrintJob = printJob;
                    val2.DataMethod = "GetBackgroundReport";
                    ((AbstractDynamicFormPlugIn)this).View.AddAction(text5, (object)val);
                }
            }
        }

        private void AddTask()
        {
            DynamicFormShowParameter val = new DynamicFormShowParameter();
            val.ParentPageId = ((AbstractDynamicFormPlugIn)this).View.PageId;
            val.FormId = "BOS_AddBackgroundPrintTask";
            val.CustomComplexParams.Add("model", ((AbstractDynamicFormPlugIn)this).Model);
            ((AbstractDynamicFormPlugIn)this).View.ShowForm(val, (Action<FormResult>)delegate
            {
                ((AbstractDynamicFormPlugIn)this).View.Refresh();
            });
        }
    }
}
